package com.yiren.manager.ctrl.elder;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.opensymphony.xwork2.util.finder.Test;
import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.Favorites;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrBedRetain;
import com.yiren.entity.YrCgIndiServiceSendOrder;
import com.yiren.entity.YrCgSendOrder;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrElderWallet;
import com.yiren.entity.YrStaffInfo;
import com.yiren.entity.YrUserVipCard;
import com.yiren.entity.YrWalletReturn;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.form.elder.YrBedRetainForm;
import com.yiren.manager.form.elder.YrElderBeHospitalForm;
import com.yiren.manager.form.elder.YrElderForm;
import com.yiren.manager.service.iface.department.YrCgIndiServiceSendOrderService;
import com.yiren.manager.service.iface.department.YrCgSendOrderService;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.elder.YrBedRetainService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.elder.YrElderWalletService;
import com.yiren.manager.service.iface.elder.YrWalletReturnService;
import com.yiren.manager.service.iface.vip.YrUserVipCardService;
import com.yiren.manager.task.DateUtil;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("bedRetain")
@Controller
public class YrBedRetainController extends GenericController<YrBedRetainForm, YrBedRetain> {

	@Autowired
	private YrBedRetainService selfService;

	@Autowired
	private YrCgIndiServiceSendOrderService cgIndiServiceSendOrderService;

	@Autowired
	private YrCgSendOrderService cgSendOrderService;

	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;

	@Autowired
	private YrStaffInfoService staffInfoService;
	
	@Autowired
	private YrElderWalletService elderWalletService;
	
	@Autowired
	private YrUserVipCardService userVipCardService;
	
	@Autowired
	private YrElderService elderService;
	
	// 保存实体
	@RequestMapping("/save")
	@ResponseBody
	public HTTPResult<YrBedRetainForm> save(String data) throws SwallowException, MyException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
		HTTPResult<YrBedRetainForm> result = new HTTPResult<YrBedRetainForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrBedRetainForm form = tool.mapper("bedRetain", YrBedRetainForm.class);
		if (null == form) {
			throwExp("param.error");
		}
		String sqlWhere = "elder_id=?1 AND (retain_status=0 OR retain_status=1)";
		QueryResult<YrBedRetain> qrBedRetain = selfService.find(YrBedRetain.class, sqlWhere,
				new Object[] { form.getElderId() });
		if (qrBedRetain.getTotalRecord() > 0) {
			throwExp("该老者保留床位尚未结束，请勿重复保留");
		}
		if (null == form.getBedRetainId() || form.getBedRetainId().isEmpty()) {
			form.setBedRetainId(UUIDGenerator.getUUID());
			form.setCreateTime(new Date());
		}
		form.setUpdateTime(new Date());
		YrBedRetain entity = ObjectUtils.objectToObject(form, YrBedRetain.class);
		entity.setRetainStartTime(new Date());
//		entity.setRetainStatus(0);

		sqlWhere = "elder_id=?1";
		YrCgIndiServiceSendOrder cgIndiServiceSendOrder = null;
		QueryResult<YrCgIndiServiceSendOrder> qrCgIndiServiceSendOrder = cgIndiServiceSendOrderService
				.find(YrCgIndiServiceSendOrder.class, sqlWhere, new Object[] { form.getElderId() });
		if (qrCgIndiServiceSendOrder.getTotalRecord() > 0) {
			cgIndiServiceSendOrder = qrCgIndiServiceSendOrder.getResultList().get(0);
			cgIndiServiceSendOrder.setStatus(1);
		}
		QueryResult<YrCgSendOrder> qrCgSendOrder = cgSendOrderService.find(YrCgSendOrder.class, sqlWhere,
				new Object[] { form.getElderId() });
		YrCgSendOrder cgSendOrder = null;
		if (qrCgSendOrder.getTotalRecord() > 0) {
			cgSendOrder = qrCgSendOrder.getResultList().get(0);
			cgSendOrder.setStatus(1);
		}
		sqlWhere = "elder_id=?1 AND be_status=0";
		YrElderBeHospital elderBeHospital = null;
//		if (isBeforeToday(form.getRetainStartTime())) {
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
					sqlWhere, new Object[] { form.getElderId()});
			if (!qrElderBeHospital.getResultList().isEmpty()) {
				elderBeHospital = qrElderBeHospital.getResultList().get(0);
				elderBeHospital.setBedStatus(1);
				entity.setRetainStatus(1);// 设置为保留状态
			}
//		}

		Favorites favorites = new Favorites();
		favorites.putFavorite(YrBedRetain.class, entity);
		favorites.putFavorite(YrCgIndiServiceSendOrder.class, cgIndiServiceSendOrder);
		favorites.putFavorite(YrCgSendOrder.class, cgSendOrder);
		favorites.putFavorite(YrElderBeHospital.class, elderBeHospital);

		selfService.addByFavorites(favorites);
		return result;
	}

	// 判断是不是今天之前(含今天)
	private static boolean isBeforeToday(Date date) {
		Calendar c = Calendar.getInstance();
		Calendar c1 = Calendar.getInstance();
		c1.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH));

		if (date.after(c.getTime())) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 保留床位结束
	 * 
	 * @return
	 * @throws MyException
	 * todo
	 */
	@RequestMapping("finish")
	@ResponseBody
	public HTTPResult<YrBedRetainForm> finish(String id) throws MyException {
		HTTPResult<YrBedRetainForm> result = new HTTPResult<YrBedRetainForm>();
		YrBedRetain bedRetain = selfService.findOne(id);
		if (null == bedRetain) {
			throwExp("找不到相关床位保留信息");
		}
		if(bedRetain.getRetainStatus()==2){
			throwExp("该保床已经结束，请勿重复操作");
		}
		bedRetain.setRetainStatus(2);// 更改为保留结束
		bedRetain.setRetainEndTime(new Date());
		String sqlWhere = "elder_id=?1 AND be_status<>2";
		QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
				sqlWhere, new Object[] { bedRetain.getElderId() });
		YrElderBeHospital elderBeHospital = null;
		if (qrElderBeHospital.getTotalRecord() == 0) {
			throwExp("未查到相关住院信息");
		}
		elderBeHospital = qrElderBeHospital.getResultList().get(0);
		elderBeHospital.setBedStatus(0);
		
//		Date startTime = bedRetain.getRetainStartTime();
		
//		Integer dayNum = DateUtil.daysOfTwo(startTime, new Date());
//		Float returnMoney = Float.valueOf(0);
//		if(elderBeHospital.getHouseTypeType()==1){
//			YrUserVipCard userVipCard = userVipCardService.findOne(elderBeHospital.getUserVipCardId());
//			returnMoney = (float) (userVipCard.getPricePerDay()*dayNum*0.2);
//		}
//		else{
//			if(elderBeHospital.getConsumptionType()==1){//半个月扣费
//				returnMoney = elderBeHospital.getBedCostPrice()/15*dayNum*(1-elderBeHospital.getDiscount());
//			}else{//一个月扣费
//				returnMoney = elderBeHospital.getBedCostPrice()/30*dayNum*(1-elderBeHospital.getDiscount());
//			}
//		}
		
//		YrWalletReturn walletReturn = new YrWalletReturn();
//		walletReturn.setElderId(bedRetain.getElderId());
//		walletReturn.setRelationId(bedRetain.getBedRetainId());
//		walletReturn.setReturnMoney(returnMoney);
//		walletReturn.setReturnTime(new Date());
//		walletReturn.setWalletReturnId(UUIDGenerator.getUUID());
//		walletReturn.setCreateTime(new Date());
//		walletReturn.setBeHospitalId(elderBeHospital.getBeHospitalId());
//		walletReturn.setSource(1);//设置返回来源为保床
		
//		sqlWhere = "elder_id=?1";
		
//		QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere, new Object[]{bedRetain.getElderId()});
//		if(qrElderWallet.getTotalRecord()==0){
//			throwExp("该老者尚未有钱包，折扣金额无法返还");
//		}
		
//		YrElderWallet elderWallet = qrElderWallet.getResultList().get(0);
//		elderWallet.setWalletBalance(elderWallet.getWalletBalance()+returnMoney);
		
		Favorites favorites = new Favorites();
		favorites.putFavorite(YrBedRetain.class, bedRetain);
		favorites.putFavorite(YrElderBeHospital.class, elderBeHospital);
//		favorites.putFavorite(YrWalletReturn.class, walletReturn);
//		favorites.putFavorite(YrElderWallet.class, elderWallet);
		// favorites.putFavorite(YrUserVipCardRecord.class, userVipCardRecord);

		selfService.finish(favorites);
		return result;
	}

	@RequestMapping("findAll")
	@ResponseBody
	public HTTPResult<YrBedRetainForm> findAll() throws Exception {
		HTTPResult<YrBedRetainForm> result = new HTTPResult<YrBedRetainForm>();
		String sqlWhere = "retain_status=1 OR retain_status=0";

		QueryResult<YrBedRetain> qr = selfService.find(YrBedRetain.class, sqlWhere, new Object[] {});

		List<YrBedRetain> entityList = qr.getResultList();

		List<YrBedRetainForm> formList = new ArrayList<YrBedRetainForm>();
		for (YrBedRetain entity : entityList) {
			YrBedRetainForm form = toForm(entity);
			sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
					sqlWhere, new Object[] { entity.getElderId() });
			if (qrElderBeHospital.getTotalRecord() > 0) {
				YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
				YrElderBeHospitalForm elderBeHospitalForm = ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class);
				YrElder elder = elderService.findOne(entity.getElderId());
				if(elder!=null){
					elderBeHospitalForm.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
				}
				form.setElderBeHospitalForm(elderBeHospitalForm);
			}
			if(null!=form.getCreateId()){
				YrStaffInfo staffInfo = staffInfoService.findOne(form.getCreateId()==null?"":form.getCreateId());
				if (null != staffInfo) {
					form.setHandler(staffInfo.getName());
				}
			}
			formList.add(form);
		}
		result.setData(formList);
		return result;
	}
	
	@RequestMapping("findBySubjectRoomId")
	@ResponseBody
	public HTTPResult<YrBedRetainForm> findBySubjectRoomId(String subjectRoomId) throws Exception {
		HTTPResult<YrBedRetainForm> result = new HTTPResult<YrBedRetainForm>();
		String sqlWhere = "(retain_status=1 OR retain_status=0) AND subject_room_id=?1";

		QueryResult<YrBedRetain> qr = selfService.find(YrBedRetain.class, sqlWhere, new Object[] { subjectRoomId });

		List<YrBedRetain> entityList = qr.getResultList();

		List<YrBedRetainForm> formList = new ArrayList<YrBedRetainForm>();
		for (YrBedRetain entity : entityList) {
			YrBedRetainForm form = toForm(entity);
			YrElderBeHospital elderBeHospital = elderBeHospitalService.findOne(entity.getBeHospitalId());
			if(null!=elderBeHospital){
				YrElderBeHospitalForm elderBeHospitalForm = ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class);
				YrElder elder = elderService.findOne(entity.getElderId());
				if(elder!=null){
					elderBeHospitalForm.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
				}
				form.setElderBeHospitalForm(elderBeHospitalForm);
			}
			if(null!=form.getCreateId()){
				YrStaffInfo staffInfo = staffInfoService.findOne(form.getCreateId());
				if (null != staffInfo) {
					form.setHandler(staffInfo.getName());
				}
			}
			formList.add(form);
		}
		result.setData(formList);

		return result;
	}

	@RequestMapping("findByElderId")
	@ResponseBody
	public HTTPResult<YrBedRetainForm> findByElderId(String elderId) throws Exception{
		HTTPResult<YrBedRetainForm> result = new HTTPResult<YrBedRetainForm>();
		
		String sqlWhere = "elder_id=?1";
		
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("createTime", "ASC");
		
		QueryResult<YrBedRetain> qr = selfService.find(YrBedRetain.class, sqlWhere, new Object[]{elderId},map);
		List<YrBedRetainForm> formList  = new ArrayList<YrBedRetainForm>();
		for(YrBedRetain entity : qr.getResultList()){
			YrBedRetainForm form = toForm(entity);
			YrStaffInfo staffInfo = staffInfoService.findOne(form.getCreateId()==null?"":form.getCreateId());
			form.setHandler(staffInfo.getName());
			
			YrElder elder = elderService.findOne(elderId);
			if(null!=elder){
				form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
			}
			
			YrElderBeHospital elderBeHospital = elderBeHospitalService.findOne(entity.getBeHospitalId());
			if(null!=elderBeHospital){
				form.setElderBeHospitalForm(ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class));
			}
			formList.add(form);
		}
		result.setData(formList);
		return result;
	}
	
	@Override
	public YrBedRetainForm toForm(YrBedRetain e) throws Exception {
		YrBedRetainForm form = ObjectUtils.objectToObject(e, YrBedRetainForm.class);
		return form;
	}

	@Override
	public YrBedRetain toEntity(YrBedRetainForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
